<?php

namespace App\Http\Model\MonitoringLink;

use App\Http\Model\Base;
use Illuminate\Support\Facades\Log;

/**
 * 监测链接-accessToken管理
 *
 * Created on 2021/11/4 17:07
 * @Author <yuxiang.zhu@asiainnovations.net>
 */
class AccessToken extends Base
{
    //from
    const FROM_HUAWEI = 'huawei';
    const FROM_VIVO = 'vivo';
    const FROM_APPLE = 'apple';

    // 华为client_id
    const CLIENT_ID_HUAWEI = '767343688505377472';


    /**
     * 表名字
     *
     * @var string
     */
    protected $table = 'monitoring_link_access_token';

    /**
     * 指示模型是否自动维护时间戳
     *
     * @var bool
     */
    public $timestamps = true;

    /**
     * 模型日期列的存储格式。
     *
     * @var string
     */
    protected $dateFormat = 'U';

    /**
     * 可以被批量赋值的属性。
     *
     * @var array
     */
    protected $fillable = ['id', 'access_token', 'refresh_token', 'token_date', 'refresh_token_date', 'from', 'created_at', 'updated_at'];

    /**
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 获取VIVO的accessToken
     *
     * Created at 2021/11/4 17:29
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @return string
     */
    public function getVIVOAccessToken(): string
    {
        $clientId = '20211104007';
        $clientSecret = '81798EC823C086A6E0A618C403F4B492B8D8E4A28D35EE29CE00D8F24268BD45';
        $url = 'https://marketing-api.vivo.com.cn/openapi/v1/oauth2/refreshToken';
        $from = self::FROM_VIVO;
        $where = ['from' => $from];
        $query = self::query()->where($where)->first();
        if (!$query) {
            return '';
        }

        $query = $query->toArray();
        $currentMillisecond = time() * 1000;
        $diffMillisecond = 24 * 3600 * 1000;
        if ($query['token_date'] - $currentMillisecond <= $diffMillisecond) {//过期时间小于等于1天了, 刷新一下
            try {
                $params = ['client_id' => $clientId, 'client_secret' => $clientSecret, 'refresh_token' => $query['refresh_token']];
                $result = curl_request($url, $params, 'urlencoded', 'GET');
                $result = json_decode($result, true);
                if ($result['code'] == 0) {
                    self::query()->where($where)->update($result['data']);
                    return $result['data']['access_token'];
                }

                return '';
            } catch (\Throwable $exception) {//发生异常
                return '';
            }
        } else {
            return $query['access_token'];
        }
    }

    /**
     * 获取华为oCPD业务access_token
     *
     * Created at 2021/11/23 19:45
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param bool $insert
     * @return string
     */
    private function getOCPDAccessToken(bool $insert = false): string
    {
        $clientId = self::CLIENT_ID_HUAWEI;
        $clientSecret = '540639ABB07360188A5EB30CE25402E50E4A0DD7221DC2F11BE42B42F4384034';
        $url = 'https://connect-api.cloud.huawei.com/api/oauth2/v1/token';
        $params = ['grant_type' => 'client_credentials', 'client_id' => $clientId, 'client_secret' => $clientSecret];
        try {
            $result = curl_request($url, $params, 'json', 'POST');
            $resultArr = json_decode($result, true);
            if (isset($resultArr['ret'])) {
                Log::info('getOcpdAccessToken=' . $result);
                return '';
            }

            $accessToken = $resultArr['access_token'];
            $tokenDate = (time() + $resultArr['expires_in']) * 1000;//毫秒
            if ($insert) {
                self::query()->create([
                    'access_token' => $accessToken,
                    'token_date' => $tokenDate,
                    'from' => self::FROM_HUAWEI,
                ]);
            } else {
                self::query()->where(['from' => self::FROM_HUAWEI])->update(['access_token' => $accessToken, 'token_date' => $tokenDate,]);
            }

            return $accessToken;
        } catch (\Throwable $exception) {//发生异常
            return '';
        }
    }

    /**
     * 获取华为的accessToken，OCPD业务用到
     *
     * Created at 2021/11/4 17:29
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @return string
     */
    public function getHuaWeiAccessToken(): string
    {
        $from = self::FROM_HUAWEI;
        $where = ['from' => $from];
        $query = self::query()->where($where)->first();
        if (!$query) {
            return $this->getOCPDAccessToken(true);
        }

        $query = $query->toArray();
        $currentMillisecond = time() * 1000;
        $diffMillisecond = 1800 * 1000;//提前30分钟
        if ($query['token_date'] - $currentMillisecond <= $diffMillisecond) {//过期时间小于等于1天了, 刷新一下
            return $this->getOCPDAccessToken();
        } else {
            return $query['access_token'];
        }
    }

    /**
     * Created at 2021/12/2 17:20
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param bool $insert
     * @return string
     */
    private function getASAAccessToken(bool $insert = false): string
    {
        $from = self::FROM_APPLE;
        $clientId = 'SEARCHADS.920b5cda-cdfa-42c4-8c7e-be69f9c3c58b';
        $clientSecret = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiIsImtpZCI6ImNhYTc4YzdmLWIxMmUtNDRhYi1hZGIzLTNjZmJlMTM0YTEwYiJ9.eyJzdWIiOiJTRUFSQ0hBRFMuOTIwYjVjZGEtY2RmYS00MmM0LThjN2UtYmU2OWY5YzNjNThiIiwiYXVkIjoiaHR0cHM6Ly9hcHBsZWlkLmFwcGxlLmNvbSIsImlhdCI6MTYzODQxMTI5OSwiZXhwIjoxNjUzOTYzMjk5LCJpc3MiOiJTRUFSQ0hBRFMuOTIwYjVjZGEtY2RmYS00MmM0LThjN2UtYmU2OWY5YzNjNThiIn0.1xRWJyjJMfGfz7Q54BBFBQhd1A4WzXtE_Y6MQh7mVTfqLiftTkuX4PGNXP7oYExEpQbiG5xVuAQu49xvHalJCQ';
        $url = 'https://appleid.apple.com/auth/oauth2/token?grant_type=client_credentials&client_id='
            . $clientId . '&client_secret=' . $clientSecret . '&scope=searchadsorg';
        try {
            $result = curl_request($url, [], 'urlencoded', 'POST');
            if (strpos($result, 'access_token') === false) {
                Log::info('getASAAccessToken=' . $result);
                return '';
            }

            $resultArr = json_decode($result, true);
            $accessToken = $resultArr['access_token'];
            $tokenDate = (time() + $resultArr['expires_in']) * 1000;//毫秒
            if ($insert) {
                self::query()->create(['access_token' => $accessToken, 'token_date' => $tokenDate, 'from' => $from,]);
            } else {
                self::query()->where(['from' => $from])->update(['access_token' => $accessToken, 'token_date' => $tokenDate,]);
            }

            return $accessToken;
        } catch (\Throwable $exception) {//发生异常
            return '';
        }
    }

    /**
     * Created at 2021/12/2 17:28
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @return string
     */
    public function getAppleASAAccessToken(): string
    {
        $from = self::FROM_APPLE;
        $where = ['from' => $from];
        $query = self::query()->where($where)->first();
        if (!$query) {
            return $this->getASAAccessToken(true);
        }

        $query = $query->toArray();
        $currentMillisecond = time() * 1000;
        $diffMillisecond = 5 * 1000;//提前5分钟
        if ($query['token_date'] - $currentMillisecond <= $diffMillisecond) {//过期重新获取
            return $this->getASAAccessToken();
        } else {
            return $query['access_token'];
        }
    }
}